(function($){
	
	var KEY = "jforest.form";
	
	var Form = function(element,options){
		this.$el = $(element);
	};
	
	Form.prototype = {
		submit:function(url,callback){
			if($.isFunction(url)){
				callback = url;
				url = this.$el.attr('action');
			}
			//获取表单数据
			var fields = this.$el.find(":input").serializeArray();
			var data = {};
		    jQuery.each( fields, function( i, field ) {
		    	data[field.name] = field.value;
		    });
			$.post(url,data,function(result){
				callback(result);
			});
		},
		set:function(url,data,callback){
			var el = this.$el;
			if(!data){data = {};}
			$.get(url,data,function(result){
				if(result){
					jQuery.each( result, function( key, value ) {
						el.find('[name="'+key+'"]').val(value);
				    });
				}
				callback(result);
			});
		},
		setNull:function(){
			this.$element[0].reset();
		}
	};
	
	$.fn.jfForm = function(){
		var args = Array.prototype.slice.call(arguments, 0);
		var value = undefined;
		this.each(function () {
			var $this = $(this);
			if (args.length === 0 || typeof(args[0]) === "object") {
				opts = args.length === 0 ? {} : $.extend({}, args[0]);
				$this.data(KEY,new Form(this,opts)); //创建控件
			}else if (typeof(args[0]) === "string"){
				var entity = $this.data(KEY);
				if(entity === undefined){
					entity = new Form(this,{}); //创建控件
					$this.data(KEY,entity);
				}
				value = entity[args[0]].apply(entity, args.slice(1));
			}else{
				 throw 'Invalid arguments to '+KEY+' plugin: ' + args;
			}
	    });
	    return (value === undefined) ? this : value;
	};
	
	$.fn.jfForm.Constructor = Form;
	
})(window.jQuery);